package rudia.org.util;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

@Component
public class HttpClientUtil {

	private String cookies;
	private HttpClient client = HttpClientBuilder.create().build();
	private final String USER_AGENT = "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19";
	private String url = "http://map.search.daum.net/mapsearch/map.daum";


	public void sendPost() throws Exception {

		HttpPost post = new HttpPost(url);

		// add header
		post.setHeader("Accept", "*/*");
		post.setHeader("Accept-Encoding", "gzip, deflate, sdch");
		post.setHeader("Accept-Language", "ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4");
		post.setHeader("User-Agent", USER_AGENT);//
		post.setHeader("Referer", "http://map.daum.net/");// d
		post.setHeader("Connection", "keep-alive");
		post.setHeader("Host", "map.search.daum.net");
		post.setHeader("Content-Type", "text/plain;charset=UTF-8");
		post.setHeader("Cookie", "TIARA=QG-BtlPlESLIrMf-hHm1nWZnJuiCD1I3kQYJsHcmsveG5lIjhfS3uRAsyYDNrqIFx-IL_NE2Y8oGXvKzFJ5RtShdvz_Kz5FH");

		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		paramList.add(new BasicNameValuePair("callback", "aaa"));
		paramList.add(new BasicNameValuePair("q", "자동차 정비"));
		paramList.add(new BasicNameValuePair("msFlag", "S"));
		paramList.add(new BasicNameValuePair("mcheck", "Y"));
		paramList.add(new BasicNameValuePair("rect", "-4005880,-2049520,3756040,2717200"));
		paramList.add(new BasicNameValuePair("page", "1"));
		paramList.add(new BasicNameValuePair("sort", "0"));

		post.setEntity(new UrlEncodedFormEntity(paramList));

		HttpResponse response = client.execute(post);
		HttpEntity entity = response.getEntity();
		System.out.println(entity.toString());
		String content = EntityUtils.toString(entity);
		System.out.println(content);
		
		int responseCode = response.getStatusLine().getStatusCode();

		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("Post parameters : " + paramList.toString());
		System.out.println("Response Code : " + responseCode);
		System.out.println(response.toString());

	}

}
